#!/usr/bin/env python

"""

This tool starts with one URL of one's profile and then tries to get as many other 
profile page of that same person by following XFN links. 

"""

from BeautifulSoup import BeautifulSoup
from optparse import OptionParser
from urllib import urlopen
import sys

def normalize(url):
      """just check for a ending / now"""
      if url.endswith("/"):
        url=url[:-1]
      return url

class XFNProfileFinder(object):
    """class for following me-relationships for pages"""

        def normalize(url):
              """just check for a ending / now"""
              if url.endswith("/"):
                url=url[:-1]
              return url

usage = "usage: %prog [options] URL"
parser = OptionParser(usage)
parser.add_option("-v", "--verbose", dest="verbose", action="store_true", help="verbose output")
(options, args) = parser.parse_args()

if len(args) != 1:
    parser.error("incorrect number of arguments")

main_url = args[0]
data = urlopen(normalize(main_url))
soup = BeautifulSoup(data)
all_urls=[normalize(ref['href']) for ref in soup.findAll("a",rel="me")]
if options.verbose and len(all_urls):
    print "found %s relationships to check" %len(all_urls)

# now backcheck for symmetrical relationships
relationships=[]

for url in all_urls:
    if options.verbose:
            print "checking %s" %url
    data = urlopen(url)
    soup = BeautifulSoup(data)
    if main_url in [normalize(ref['href']) for ref in soup.findAll("a",rel="me")]:
        if options.verbose:
            print "found symmetrical relationship for %s" %main_url
        relationships.append(url)

print "found %s symmetrical relationships: " %len(relationships)
for url in relationships:
    print url
    
    


